package com.qny.ai.service.impl;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.qny.ai.config.AiVendorsConfig;
import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.Map;

@Slf4j
@Service
@RequiredArgsConstructor
public class QiniuVoiceService {

    private final AiVendorsConfig cfg;
    private final ObjectMapper mapper = new ObjectMapper();
    private final RestTemplate rest = new RestTemplate();

    public String asrByUrl(String url, String format) {
        try {
            // 使用七牛云的正确ASR API端点 - 根据官方文档
            String endpoint = "https://openai.qiniu.com/v1/voice/asr";
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            headers.set("Authorization", "Bearer " + cfg.getApiKey());
            
            // 检查API密钥
            if (cfg.getApiKey() == null || cfg.getApiKey().trim().isEmpty()) {
                log.error("[QINIU_ASR] ERROR: API key is null or empty!");
                return "";
            }
            log.info("[QINIU_ASR] Using API key: " + cfg.getApiKey().substring(0, Math.min(10, cfg.getApiKey().length())) + "...");
            
            Map<String, Object> body = new HashMap<>();
            body.put("model", "asr");
            Map<String, Object> audio = new HashMap<>();
            audio.put("format", format);
            audio.put("url", url);
            body.put("audio", audio);
            
            HttpEntity<Map<String, Object>> req = new HttpEntity<>(body, headers);
            String res = rest.postForObject(endpoint, req, String.class);
            
            log.info("[QINIU_ASR] Request: " + mapper.writeValueAsString(body));
            log.info("[QINIU_ASR] Response: " + res);
            
            // 检查响应是否包含错误信息
            if (res.contains("\"error\"")) {
                log.warn("[QINIU_ASR] API returned error response");
                return "";
            }
            
            JsonNode root = mapper.readTree(res);
            // 根据官方文档，响应结构为: data.result.text
            String result = root.path("data").path("result").path("text").asText("");
            
            log.info("[QINIU_ASR] Extracted text: " + result);
            return result;
            
        } catch (Exception e) {
            log.error("[QINIU_ASR] Error: " + e.getMessage());
            e.printStackTrace();
            return "";
        }
    }

    public String ttsToBase64(String text, String voiceType, String encoding) {
        try {
            // 清理文本，移除可能导致TTS错误的特殊字符
            String cleanedText = cleanTextForTTS(text);
            if (cleanedText.trim().isEmpty()) {
                log.warn("[QINIU_TTS] Text is empty after cleaning, skipping TTS");
                return "";
            }
            
            // 使用七牛云的正确TTS API端点 - 根据官方文档
            String endpoint = "https://openai.qiniu.com/v1/voice/tts";
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            headers.set("Authorization", "Bearer " + cfg.getApiKey());
            
            // 根据七牛云TTS API官方文档，正确的请求格式应该是嵌套结构：
            Map<String, Object> body = new HashMap<>();
            
            // audio 对象
            Map<String, Object> audio = new HashMap<>();
            audio.put("voice_type", voiceType);
            audio.put("encoding", encoding);
            audio.put("speed_ratio", 1.0);
            
            // request 对象
            Map<String, Object> request = new HashMap<>();
            request.put("text", cleanedText);
            
            // 组装请求体 - 根据官方文档，audio在前，request在后
            body.put("audio", audio);
            body.put("request", request);
            
            HttpEntity<Map<String, Object>> req = new HttpEntity<>(body, headers);
            String res = rest.postForObject(endpoint, req, String.class);
            
            log.info("[QINIU_TTS] Request: " + mapper.writeValueAsString(body));
//            System.out.println("[QINIU_TTS] Response: " + res);
            
            JsonNode root = mapper.readTree(res);
            // 根据官方文档，响应结构为: data (base64编码的音频数据)
            String result = root.path("data").asText("");
            
            log.info("[QINIU_TTS] Extracted audio: " + (result.length() > 0 ? "Base64 audio data" : "empty"));
            return result;
            
        } catch (Exception e) {
            log.error("[QINIU_TTS] Error: " + e.getMessage());
            // 如果是网络错误，尝试重试一次
            if (e.getMessage().contains("Connection reset") || e.getMessage().contains("I/O error")) {
                log.info("[QINIU_TTS] Network error detected, retrying once...");
                try {
                    Thread.sleep(1000); // 等待1秒后重试
                    
                    // 重新构建请求参数
                    String retryEndpoint = "https://openai.qiniu.com/v1/voice/tts";
                    HttpHeaders retryHeaders = new HttpHeaders();
                    retryHeaders.setContentType(MediaType.APPLICATION_JSON);
                    retryHeaders.set("Authorization", "Bearer " + cfg.getApiKey());
                    
                    Map<String, Object> retryBody = new HashMap<>();
                    Map<String, Object> retryAudio = new HashMap<>();
                    retryAudio.put("voice_type", voiceType);
                    retryAudio.put("encoding", encoding);
                    retryAudio.put("speed_ratio", 1.0);
                    
                    Map<String, Object> retryRequest = new HashMap<>();
                    retryRequest.put("text", text);
                    
                    retryBody.put("audio", retryAudio);
                    retryBody.put("request", retryRequest);
                    
                    HttpEntity<Map<String, Object>> retryReq = new HttpEntity<>(retryBody, retryHeaders);
                    String res = rest.postForObject(retryEndpoint, retryReq, String.class);
                    JsonNode root = mapper.readTree(res);
                    String result = root.path("data").asText("");
                    log.info("[QINIU_TTS] Retry successful, extracted audio: " + (result.length() > 0 ? "Base64 audio data" : "empty"));
                    return result;
                } catch (Exception retryException) {
                    log.error("[QINIU_TTS] Retry failed: " + retryException.getMessage());
                }
            }
            e.printStackTrace();
            return "";
        }
    }
    
    /**
     * 清理文本，移除可能导致TTS错误的特殊字符
     */
    private String cleanTextForTTS(String text) {
        if (text == null || text.trim().isEmpty()) {
            return "";
        }
        
        // 移除可能导致TTS错误的特殊字符和表情符号
        String cleaned = text
            // 移除所有emoji和特殊符号
            .replaceAll("[\uD83C-\uDBFF\uDC00-\uDFFF]+", "") // 所有emoji
            .replaceAll("[\u2600-\u26FF]", "") // 杂项符号
            .replaceAll("[\u2700-\u27BF]", "") // 装饰符号
            .replaceAll("[\u1F600-\u1F64F]", "") // 表情符号
            .replaceAll("[\u1F300-\u1F5FF]", "") // 杂项符号和象形文字
            .replaceAll("[\u1F680-\u1F6FF]", "") // 交通和地图符号
            .replaceAll("[\u1F1E0-\u1F1FF]", "") // 区域指示符号
            .replaceAll("[\u1F900-\u1F9FF]", "") // 补充符号和象形文字
            .replaceAll("[\u1FA70-\u1FAFF]", "") // 符号和象形文字扩展-A
            // 移除特定问题字符
            .replaceAll("[🌟✨⭐💫]", "") // 星星相关符号
            .replaceAll("[\\(\\)\\[\\]\\{\\}]", "") // 括号
            .replaceAll("[•̀ᴗ•́]", "") // 特殊Unicode字符
            .replaceAll("[و]", "") // 阿拉伯字符
            .replaceAll("[✧ω✧]", "") // 特殊符号组合
            // 移除颜文字和特殊字符组合
            .replaceAll("[\\(\\)\\[\\]\\{\\}]", "") // 各种括号
            .replaceAll("[•̀ᴗ•́]", "") // 颜文字组合
            .replaceAll("[•̀ᴗ•́]و", "") // 颜文字+阿拉伯字符
            .replaceAll("[\u0300-\u036F]", "") // 组合用附加符号
            .replaceAll("[\u1F000-\u1F9FF]", "") // 补充符号和象形文字
            .replaceAll("[\u2000-\u206F]", "") // 一般标点符号
            .replaceAll("[\u2070-\u209F]", "") // 上标和下标
            .replaceAll("[\u20A0-\u20CF]", "") // 货币符号
            .replaceAll("[\u2100-\u214F]", "") // 字母式符号
            .replaceAll("[\u2150-\u218F]", "") // 数字形式
            .replaceAll("[\u2190-\u21FF]", "") // 箭头
            .replaceAll("[\u2200-\u22FF]", "") // 数学运算符
            .replaceAll("[\u2300-\u23FF]", "") // 杂项技术符号
            .replaceAll("[\u2400-\u243F]", "") // 控制图片
            .replaceAll("[\u2440-\u245F]", "") // 光学字符识别
            .replaceAll("[\u2460-\u24FF]", "") // 带圈字母数字
            .replaceAll("[\u2500-\u257F]", "") // 制表符
            .replaceAll("[\u2580-\u259F]", "") // 方块元素
            .replaceAll("[\u25A0-\u25FF]", "") // 几何图形
            .replaceAll("[\u2600-\u26FF]", "") // 杂项符号
            .replaceAll("[\u2700-\u27BF]", "") // 装饰符号
            .replaceAll("[\uD83D\uDE00-\uD83D\uDE4F]", "") // 表情符号范围
            .replaceAll("[\uD83C\uDF00-\uD83D\uDDFF]", "") // 杂项符号和象形文字范围
            .replaceAll("[\uD83D\uDE80-\uD83D\uDEFF]", "") // 交通和地图符号范围
            .replaceAll("[\uD83C\uDDE0-\uD83C\uDDFF]", "") // 区域指示符号范围
            .replaceAll("\\s+", " ") // 多个空格合并为一个
            .trim();
        
        // 如果清理后为空，返回原始文本的前100个字符
        if (cleaned.isEmpty()) {
            cleaned = text.substring(0, Math.min(100, text.length())).trim();
        }
        
        log.debug("[QINIU_TTS] Original text: " + text);
        log.debug("[QINIU_TTS] Cleaned text: " + cleaned);
        
        return cleaned;
    }
    
    /**
     * 获取音色列表
     */
    public String getVoiceList() {
        try {
            String endpoint = "https://openai.qiniu.com/v1/voice/list";
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            headers.set("Authorization", "Bearer " + cfg.getApiKey());
            
            log.info("[QINIU_VOICE_LIST] Using API key: " + cfg.getApiKey().substring(0, 10) + "...");
            log.info("[QINIU_VOICE_LIST] Request endpoint: " + endpoint);
            
            HttpEntity<String> req = new HttpEntity<>(headers);
            
            // 使用正确的GET请求方式
            ResponseEntity<String> response = rest.exchange(
                endpoint, 
                HttpMethod.GET, 
                req, 
                String.class
            );
            
            String res = response.getBody();
            log.info("[QINIU_VOICE_LIST] Response: " + res);
            return res;
            
        } catch (Exception e) {
            log.error("[QINIU_VOICE_LIST] Error: " + e.getMessage());
            e.printStackTrace();
            return "{}";
        }
    }
}


